/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: AlarmClientExample.cpp,v 1.3 2009-05-13 07:18:15 amaula Exp $
 *
 * \file
 * \brief Example client for Alarm interface.
 * \author Antti Maula <antti.maula@tkk.fi>
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string>
#include "owndebug.h"
#include "ownutils.h"
#include "binbag.h"
#include "AlarmClient.hpp"

//*****************************************************************************
// Include GIMI in proper way
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
// Set initial verbosity level to 1
static int verbose = 1;
//*****************************************************************************
// Choose your namespace
using namespace MaCI;
using namespace MaCI::Alarm;
//*****************************************************************************
// Running?
static volatile bool run = true;
static ownThreadHandle signalHandlerThread;
//*****************************************************************************
static std::string datasource;
static std::string datasourceMaCISL;
static int clientMinor = 0;
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************


// Example for using the callback.
class CAlarmClientCallbackExample : public MaCI::Alarm::CAlarmClientCallback
{
public:
  CAlarmClientCallbackExample() {
  }

  ~CAlarmClientCallbackExample() {
  }
protected:
  void OnAlarmDataEvent(const CAlarmData &aData, 
                        const unsigned int aDataSequence,
                        CAlarmClient &aAlarmClient) {
    dPrint(2,"Got AlarmDataEvent %u through callback from Client %p:", 
           aDataSequence, &aAlarmClient);
    aData.Print(3);
  }
};
//*****************************************************************************
//*****************************************************************************

static int SignalHandlerThread(void *)
{
  dPrint(8, "Signal handler thread (%ld) starting...", pthread_self());

  while (run) {
    // Now, wait for requested signals to arrive
    int sig;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGTERM);
    sigaddset(&mask, SIGPIPE);
    sigaddset(&mask, SIGHUP);
    sigwait(&mask, &sig);

    // Got signal, sigwait returned!
    dPrint(1,"Got Signal '%d' (%s)", sig, strsignal(sig));

    // What to do?
    switch(sig) {
    case SIGINT:
    case SIGTERM:
    case SIGPIPE:
    case SIGHUP:
      run = false;
      ownSleep_ms(1000);
      break;
      
    default:
      dPrint(1,"Unhandled signal! Ignore!");
      break;
    }
  }
  return 0;
}
//*****************************************************************************

static void InitSignalHandler(void)
{
  // Now; Set to BLOCK ALL SIGNALS
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGPIPE);
  sigaddset(&mask, SIGHUP);
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  
  // Start signal handler thread
  signalHandlerThread = ownThread_Create((void*)SignalHandlerThread, NULL);
}
//*****************************************************************************
//*****************************************************************************

/**
 * All MaCI modules should support these parameters with exactly these names
 * *** DO NOT CHANGE NOR DELETE ANY OF THEM ***
 * Howevery, feel free to add new parameters as you wish.
 */
static void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tAlarmClientExample [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-s name]\t\t\tSpecify the data source\n");
  fprintf(stderr,"  \t\t\t\tOR\n");
  fprintf(stderr,"  [-S name]\t\t\tSpecify the data source by MaCISL\n");
  fprintf(stderr,"  [-m minor]\t\t\tSpecify the data source minor number\n\n");
  
  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************

static int alarmWatch(CAlarmClient *ac)
{
  CAlarmData ad;
  bool r;
  while(run) {
    r = ac->GetAlarmEvent(ad, 1000);
    if (r) {
      const TAlarmEvent *ae = ad.GetAlarmEvent();
      const TText *at = ad.GetText();

      if (ae) {
        char str[80] = "-------------------------------------------------------------------------------";
        int i = sprintf(str+2," Event: type:%d, timeout:%d, flags:%d, id:%d",
                        ae->type, ae->timeout_s, ae->flags, ae->id);
        str[2+i] = ' ';
        fprintf(stdout, "%s\n", str);
      }
      if (at) {
        fprintf(stdout,
                "-------------------------------------------------------------------------------\n"
                "%s\n"
                "*******************************************************************************\n", 
                at->text);
      }
      
      dPrint(2,"Got new AlarmData Event from client %p", ac);
      ad.Print(3);
    }
  }
  
  return 0;
}
//*****************************************************************************

static int ExecuteExampleClient(gimi::GIMI &g)
{
  // This will NOT compile, as there is no such client as
  // 'example_client'.  It is here for an example only!
  CAlarmClientCallbackExample acce;
  CAlarmClient ac(&g, clientMinor);
  CAlarmData ad;
  ownThreadHandle alarmWatchThread;

  srandom(time(NULL));

  ad.CreateInternalBinBag();

  // Assign default target.
  if (datasource.size()) {
    ac.SetDefaultTarget(datasource);

  } else {
    // GIMI is Open(), so we can execute this.
   ac.SetDefaultTarget(MaCICtrl::SMaCISL(datasourceMaCISL), 10000);
   
  }

  // Assign callback
  ac.SetAlarmClientCallback(&acce);
  
  // Open.
  if (ac.Open() == KMaCIOK) {
    dPrint(2,"Succesfully Open():ed AlarmClient!");
    alarmWatchThread = ownThread_Create((void*)alarmWatch, &ac);

    const TCommand c(KCommandClientKeepalive, 0);
    ad.SetCommand(c);
    
    while(run) {
      ac.SendCommand(ad);


      // Wait for a moment.
      const unsigned int sleepTime = 1000 + random() % 5000;
      dPrint(3,"Sleeping for %u milliseconds...", sleepTime);
      ownSleep_ms(sleepTime);
      //      ownSleep_ms(1000);
    }


  } else {
    dPrint(1,"Failed to Open() AlarmClient.");

  }


  return 0;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

int main(int argc, char *argv[]) 
{
  // GIMnet parameters
  std::string gimnetAP = "asrobo.hut.fi";
  int gimnetAPPort = 40002;
  std::string gimnetName;

  // setup signal handling
  InitSignalHandler();

  // Objects
  gimi::GIMI g;

  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(1);
  const std::string logfile = std::string(argv[0]) + ".log";
  debugSetLogFilename(logfile.c_str());

  // Greet
  fprintf(stderr,
	  "\n%s - $Revision: 1.3 $\n", argv[0]);

  /////////////////////////////////////////////////////////////////////////////
  // Parse parameters - Remember: ** DO NOT MODIFY OR DELETE ANY OF THIS **
  // _Add_ anything as you wish.
  ///////////////////////////////////////////////////////////////////////////// 
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "m:n:u:p:s:S:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////
    case 'm':
      clientMinor = atoi(optarg);
      dPrint(3,"Using Source minor: %d", clientMinor);
      break;

    case 's':
      datasource = optarg;
      dPrint(3,"Using DataSource '%s'", optarg);
      break;

    case 'S':
      datasourceMaCISL = optarg;
      dPrint(3,"Using DataSource MaCISL '%s'", optarg);
      break;

      /////////////////////////////////////////////////////////////////////////
      /// Add here anything you need.
      /////////////////////////////////////////////////////////////////////////

      /////////////////////////////////
      ///// MaCI/GIMnet parameters ////
      /////////////////////////////////
    case 'n':
      gimnetName = optarg;
      dPrint(3,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(3,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(3,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }
  
  /////////////////////////////////////////////////////////////////////////////
  // Execute connection to GIMnet.
  /////////////////////////////////////////////////////////////////////////////
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(1,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(2,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
    // GIMnet connection OK, now execute module.
    r = ExecuteExampleClient(g);
  }

  return 0;
}
//*****************************************************************************
//*****************************************************************************
/******************************************************************************
 * 
 * $Log: not supported by cvs2svn $
 * Revision 1.2  2009-04-08 07:08:21  amaula
 * Merged in 'MaCI-examples-restructuring-branch'
 *
 * Revision 1.1.2.1  2009-03-20 09:15:29  amaula
 * Structural change part I
 *
 * Revision 1.4  2009-01-12 13:46:45  amaula
 * Merged in branch: MaCI-interface-Alarm-callback-implementation-branch
 *
 * Revision 1.3.2.2  2009-01-12 13:44:35  amaula
 * Example updated.
 *
 * Revision 1.3.2.1  2009-01-09 13:09:43  amaula
 * Added implementation for Alarm callback.
 *
 * Revision 1.3  2009-01-08 12:54:16  amaula
 * Fixed interface.
 *
 * Revision 1.2  2008-12-22 13:20:00  amaula
 * Support for minor number added.
 *
 * Revision 1.1  2008-11-07 11:12:46  amaula
 * Lots of misc. changes.
 *
 *
 *
 *****************************************************************************/
//*****************************************************************************
//*****************************************************************************


